package com.kucun.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.NetworkInterface;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Random;
import java.util.UUID;
/**
 * 工具类
 * @author mato
 *
 */
public class StrUtil {
    /**
     * Description :将值为 null 的转换成 “”；
     * @param str
     * @return  @return result
     */
	public static  String   nullToblanks(String   str) 
	{ 
	        if(str==null||str.equals(null)||str.equals("null"))  
	        	return   ""; 
	        return   str; 
	} 
	public static Date getDateStr(String dates) throws ParseException {
		  // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		   Date date = (Date) sdf.parse(dates);
		   return date;
	}
	/**
	 * Description : 转码
	 * @param str
	 * @param oldcoding 原来的编码
	 * @param newcoding 需转换成的编码
	 * @return coding
	 */
	  public static String getToTranscoding(String str,String oldcoding,String newcoding){
		  String coding="";
		  if(!("").equals(nullToblanks(str))){
		try {
			coding = new String(str.getBytes(oldcoding),newcoding);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
		return coding;
	  }
		/**
		 * Description :获取当前系统时间
		 * yyyy-MM-dd HH:mm:ss
		 * @return str
		 */
		public static String getCurrentDateStr() {
			   Date date = new Date();
			   String str = null;
			   SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			   str = df.format(date);
			   return str;
		}
		/**
		 * 获取当前时间+随机数组成的序列码
		 * @return
		 */
		public static String getDateSerialNumber(){
			  java.util.Date dt =  new java.util.Date();  
			  SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
			  Random ra=new Random();
			  int b=ra.nextInt(1000);
			  String str=sdf.format(dt)+b;
			  return str;
		}
	  /**
	   * Description : 删除文件，可以是单个文件或文件夹
	　　* @param folderPath 文件夹完整绝对路径
	　　* @return flag 文件删除成功返回true,否则返回false
	　　*/
	     public static boolean delFolder(String folderPath) {
	    	 boolean flag = false;
	     try {
	        delAllFile(folderPath); //删除完里面所有内容
	        String filePath = folderPath;
	        filePath = filePath.toString();
	        java.io.File myFilePath = new java.io.File(filePath);
	        myFilePath.delete(); //删除空文件夹
	        flag=true;
	     } catch (Exception e) {
	       e.printStackTrace(); 
	     }
		return flag;
	}
	/**
	 * Description : 删除指定文件夹下所有文件
	 * @param path 文件夹完整绝对路径
	 * @return  flag
	 */
	   public static boolean delAllFile(String path) {
	       boolean flag = false;
	       File file = new File(path);
	       if (!file.exists()) {
	         return flag;
	       }
	       if (!file.isDirectory()) {
	         return flag;
	       }
	       String[] tempList = file.list();
	       File temp = null;
	       for (int i = 0; i < tempList.length; i++) {
	          if (path.endsWith(File.separator)) {
	             temp = new File(path + tempList[i]);
	          } else {
	              temp = new File(path + File.separator + tempList[i]);
	          }
	          if (temp.isFile()) {
	             temp.delete();
	          }
	          if (temp.isDirectory()) {
	             delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
	             delFolder(path + "/" + tempList[i]);//再删除空文件夹
	             flag = true;
	          }
	       }
	       return flag;
	     }
 /**  
      * 删除单个文件  
      * @param   fileName    被删除文件的文件名  
      * @return 单个文件删除成功返回true,否则返回false  
      */  
     public static boolean deleteFile(String fileName){  
    	 boolean k=false;
    	 try{
         File file = new File(fileName);   
         if(file.isFile() && file.exists()){   
             k=file.delete();   
             System.out.println("删除单个文件成功！");     
         }else{   
             System.out.println("没有文件可删！");   
             k=false;
         }  
    	 }catch (Exception e) {
			e.printStackTrace();
		}
    	 return k;
     }   
	     /** 
		   * JDK1.6新特性获取网卡MAC地址 
		   */ 
		  public static String getMac() { 
			  String macs="";
		    try { 
		      Enumeration<NetworkInterface> el = NetworkInterface.getNetworkInterfaces(); 
		      StringBuilder builder = new StringBuilder(); 
		      while (el.hasMoreElements()) { 
		        byte[] mac = el.nextElement().getHardwareAddress(); 
		        if (mac == null) 
		          continue; 
		        for (byte b : mac) { 
		          builder.append(hexByte(b)); 
		          builder.append("-"); 
		        } 
		      } 
		        if(builder.toString().equals("")){    	
		        }else{
		         macs= builder.toString().substring(0,builder.toString().length()-1); 
		        }
		    } catch (Exception exception) { 
		      exception.printStackTrace(); 
		    } 
		   
		    return Md5(macs); 
		  }  
		 // 返回一个字节的十六进制字符串 
		  static String hexByte(byte b) { 
		    String s = "000000" + Integer.toHexString(b); 
		    return s.substring(s.length() - 2); 
		  } 
			/**
			 * Description :mac地址用md5加密
			 * @param plainText
			 * @return stirng
			 */
		public static  String  Md5(String plainText ) { 
				StringBuffer buf = new StringBuffer(""); 
		    	try { 
		    	MessageDigest md = MessageDigest.getInstance("MD5"); 
		    	md.update(plainText.getBytes()); 
		    	byte b[] = md.digest(); 
		    	int i; 
		    	for (int offset = 0; offset < b.length; offset++) { 
		    	i = b[offset]; 
		    	if(i<0) i+= 256; 
		    	if(i<16) 
		    	buf.append("0"); 
		    	buf.append(Integer.toHexString(i)); 
		    	} 
		    	//System.out.println("result: " + buf.toString());//32位的加密 
		    	//System.out.println("result: " + buf.toString().substring(8,24));//16位的加密 
		    	} catch (NoSuchAlgorithmException e) { 
		    	// TODO Auto-generated catch block 
		    	e.printStackTrace(); 
		    	}
		    	return SHA(buf.toString());
		    	} 
			
		/**
		 * Description :SHA 加密mac地址
		 */
		 public static  String SHA(String plainText ) { 
			    	StringBuffer buf = new StringBuffer("");
			    	try { 
			    	MessageDigest md = MessageDigest.getInstance("SHA");   //sha
			    	md.update(plainText.getBytes()); 
			    	byte b[] = md.digest(); 
			    	int i; 
			    	for (int offset = 0; offset < b.length; offset++) { 
			    	i = b[offset]; 
			    	if(i<0) i+= 256; 
			    	if(i<16) 
			    	buf.append("0"); 
			    	buf.append(Integer.toHexString(i)); 
			    	} 
			    	//System.out.println("resultHSA: " + buf.toString());//32位的加密    92a3566e675381dc9553e3ca43dbc5bae98c7437
			    	//System.out.println("result: " + buf.toString().substring(8,24));//16位的加密 
			    	} catch (NoSuchAlgorithmException e) { 
			    	// TODO Auto-generated catch block 
			    	e.printStackTrace(); 
			    	} 
			    	return buf.toString();
			    	}
		 /**
		  * 读取服务器上文件
		  * @param FileName
		  * @return
		  * @throws IOException
		  */
		 public String ReadUrl(String FileName) throws IOException{
			   String read;
			   String readStr = "";
			   try{
			   URL   url   =   new   URL(FileName);
			      HttpURLConnection   urlCon   =   (HttpURLConnection)url.openConnection();
			      urlCon.setConnectTimeout(5000);
			      urlCon.setReadTimeout(5000);
			   BufferedReader br = new BufferedReader(new InputStreamReader( urlCon.getInputStream()));
			     while ((read = br.readLine()) != null) {
			              readStr = readStr + read;
			     }
			     br.close();
			   }
			  catch (IOException e) {
			   // TODO Auto-generated catch block
			   readStr = "f";
			  }
			  return readStr;
			  }
		 /**
		      * 功能：Java读取txt文件的内容
		      * 步骤：1：先获得文件句柄
		      * 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
		      * 3：读取到输入流后，需要读取生成字节流
		      * 4：一行一行的输出。readline()。
		      * 备注：需要考虑的是异常情况
		      * @param filePath
		      */
		 public static String readtxt(String fileurl){
			 String str="";
			 try{
				BufferedReader br=new BufferedReader(new FileReader(fileurl));
			    String r=br.readLine();
				while(r!=null){
				str+=r;
				r=br.readLine();
			}
			 }catch (Exception e) {
				System.out.println("文件不存在");
			}
			return str;
}
		 /** 
		   * JDK1.6新特性获取网卡MAC地址 
		   */ 
		  public static String getMacs() { 
			  String macs="";
		    try { 
		      Enumeration<NetworkInterface> el = NetworkInterface.getNetworkInterfaces(); 
		      StringBuilder builder = new StringBuilder(); 
		      while (el.hasMoreElements()) { 
		        byte[] mac = el.nextElement().getHardwareAddress(); 
		        if (mac == null) 
		          continue; 
		        for (byte b : mac) { 
		          builder.append(hexByte(b)); 
		          builder.append("-"); 
		        } 
		      } 
		        if(builder.toString().equals("")){    	
		        }else{
		         macs= builder.toString().substring(0,builder.toString().length()-1); 
		        }
		    } catch (Exception exception) { 
		      exception.printStackTrace(); 
		    } 
		   
		    return macs; 
		  } 		 
		 
		
}
